package controller;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Gebruiker;
import model.Veiling;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import database.ReadDAO;
import database.WriteDAO;

/**
 * Servlet implementation class editController
 */
public class editController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public editController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		WriteDAO write = new WriteDAO();
		ReadDAO read = new ReadDAO();
		HttpSession session = request.getSession();
		String action = request.getParameter("action");
		if(action != null && action.equals("delete")){
			Veiling veiling = read.getVeiling(Integer.parseInt(request.getParameter("veilingid")));
			Gebruiker gebruiker = (Gebruiker) session.getAttribute("gebruiker");
			if(veiling.getVerkoper().getId() == gebruiker.getId()){
				write.deleteVeiling(Integer.parseInt(request.getParameter("veilingid")));
				File foto = new File(getServletContext().getRealPath("") + (veiling.getFoto().toString()).substring(1));
				if(!foto.getName().equals("default.jpg")){
					foto.delete();
				}
				response.sendRedirect("./VeilingController?action=myAuctions");
			}else{
				request.setAttribute("Veilingen", read.getVeilingen());
				request.setAttribute("error", "notallowedtodelete");
				RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/errorpages/error.jsp");
				view.forward(request, response);
				return;
			}
			
		}else{
			int veilingid = Integer.parseInt(request.getParameter("veilingid"));
			request.setAttribute("veiling", read.getVeiling(veilingid));

			RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/editauction.jsp");
			view.forward(request, response);
			return;
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String foto = "";
		String titel = "";
		Double prijs = 0.00;
		int veilingid = -1;
		String omschrijving = "";
		boolean newFoto = true;
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);

		// check if the http request is a multipart request
		// with other words check that the http request can have uploaded files
		if (isMultipart) {

			//  Create a factory for disk-based file items
			FileItemFactory factory = new DiskFileItemFactory();
			//  Create a new file upload handler
			ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
			// Set upload parameters
			// See Apache Commons FileUpload for more information
			// http://jakarta.apache.org/commons/fileupload/using.html
			servletFileUpload.setSizeMax(-1);

			try {

				String directory = "";

				// Parse the request
				List<?> items = servletFileUpload.parseRequest(request);

				// Process the uploaded items
				Iterator<?> iter = items.iterator();

				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();

					// the param tag directory is sent as a request parameter to
					// the server
					// check if the upload directory is available
					if (item.isFormField()) {

						String name = item.getFieldName();

						if (name.equalsIgnoreCase("directory")) {
							directory = item.getString();
						}
						if(name.equals("naam")){
							titel = item.getString();
						}
						if(name.equals("prijs")){
							prijs = Double.parseDouble(item.getString().replaceAll(",", "."));
						}
						if(name.equals("beschrijving")){
							omschrijving = item.getString();
						}
						if(name.equals("veilingid")){
							veilingid = Integer.parseInt(item.getString());
						}

						// retrieve the files
					} else {

						// the fileNames are urlencoded
						String fileName = URLDecoder.decode(item.getName(), "UTF-8");

						File file = new File(directory, fileName);
						file = new File(getServletContext().getRealPath("/images/"), file.getPath());

						foto = "./images/"+file.getName();

						if(file.getName().equals("")){
							newFoto = false;
						}

						// retrieve the parent file for creating the directories
						File parentFile = file.getParentFile();

						if (parentFile != null) {
							parentFile.mkdirs();
						}
						if(newFoto){
							// writes the file to the filesystem
							item.write(file);
						}

					}
				}

			} catch (Exception e) {
				e.printStackTrace();
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			}

			response.setStatus(HttpServletResponse.SC_OK);

		} else {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
		}
		WriteDAO write = new WriteDAO();
		if(!newFoto){
			ReadDAO read = new ReadDAO();
			foto = read.getVeiling(veilingid).getFoto().toString();
		}if(titel.equals("") || omschrijving.equals("")){
			request.setAttribute("veilingid", veilingid);
			request.setAttribute("error", "emptyfieldseditauction");
			RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/errorpages/error.jsp");
			view.forward(request, response);
			return;
		}else{
			write.updateVeiling(titel, foto, prijs, omschrijving, veilingid);

			response.sendRedirect("VeilingController?action=fullauction&veiling=" + veilingid);
		}

	}

}
